#import "MarqueeLabel.h"

@interface MarqueeLabel ()

@property (strong, nonatomic) UILabel *label1;
@property (strong, nonatomic) UILabel *label2;
@property (strong, nonatomic) UIView *containerView;
@property (nonatomic) CGFloat textWidth;
@property (nonatomic) BOOL needsScrolling;
@property (nonatomic) BOOL isScrolling;
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic) CFTimeInterval lastUpdateTime;
@property (nonatomic) CGFloat contentOffset;
@property (nonatomic) CGFloat scrollStep;
@property (nonatomic) CGFloat loopStartPosition;

@end

@implementation MarqueeLabel

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.clipsToBounds = YES;
    _scrollSpeed = 30.0;
    _contentOffset = 0.0;
    
    // 创建容器视图
    _containerView = [[UIView alloc] init];
    _containerView.backgroundColor = [UIColor clearColor];
    [self addSubview:_containerView];
    
    // 创建滚动标签
    _label1 = [[UILabel alloc] init];
    _label2 = [[UILabel alloc] init];
    [_containerView addSubview:_label1];
    [_containerView addSubview:_label2];
    
    // 设置初始值
    _text = @"";
    _font = [UIFont systemFontOfSize:17.0];
    _textColor = [UIColor blackColor];
    _textAlignment = NSTextAlignmentLeft;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 计算文本实际宽度
    _textWidth = [self.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, self.frame.size.height)
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName: self.font}
                                        context:nil].size.width;
    
    // 判断是否需要滚动
    _needsScrolling = _textWidth > self.frame.size.width;
    
    // 设置容器视图尺寸
    self.containerView.frame = self.bounds;
    
    if (_needsScrolling) {
        // 容器宽度为文本宽度的2倍+视图宽度（为了平滑滚动）
        CGFloat containerWidth = MAX(_textWidth * 2 + self.bounds.size.width, self.bounds.size.width * 2);
        self.containerView.frame = CGRectMake(0, 0, containerWidth, self.bounds.size.height);
        
        // 配置标签属性
        _label1.text = self.text;
        _label1.font = self.font;
        _label1.textColor = self.textColor;
        _label1.textAlignment = NSTextAlignmentLeft;
        _label1.frame = CGRectMake(0, 0, _textWidth, self.bounds.size.height);
        
        _label2.text = self.text;
        _label2.font = self.font;
        _label2.textColor = self.textColor;
        _label2.textAlignment = NSTextAlignmentLeft;
        _label2.frame = CGRectMake(_textWidth, 0, _textWidth, self.bounds.size.height);
        
        // 确保第二个标签可见
        _label2.hidden = NO;
        
        // 重置内容偏移
        _contentOffset = 0;
        [self updateContainerPosition];
        
        // 重启滚动
        [self restartScrolling];
    } else {
        // 单行居中布局
        _label1.frame = self.bounds;
        _label1.text = self.text;
        _label1.font = self.font;
        _label1.textColor = self.textColor;
        _label1.textAlignment = self.textAlignment;
        
        // 隐藏第二个标签
        _label2.hidden = YES;
        [self stopScrolling];
    }
}

- (void)updateContainerPosition {
    CGFloat containerWidth = self.containerView.frame.size.width;
    CGFloat scrollWidth = self.textWidth;
    CGFloat viewWidth = self.bounds.size.width;
    
    // 实现循环滚动：当内容滚动超过文本宽度时重置
    if (_contentOffset <= -scrollWidth) {
        _contentOffset += scrollWidth;
    }
    
    // 设置容器视图的位置
    self.containerView.frame = CGRectMake(_contentOffset, 0, containerWidth, self.bounds.size.height);
}

#pragma mark - Properties
- (void)setText:(NSString *)text {
    _text = [text copy];
    [self setNeedsLayout];
}

- (void)setFont:(UIFont *)font {
    _font = font;
    [self setNeedsLayout];
}

- (void)setTextColor:(UIColor *)textColor {
    _textColor = textColor;
    [self setNeedsLayout];
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment {
    _textAlignment = textAlignment;
    [self setNeedsLayout];
}

- (void)setScrollSpeed:(CGFloat)scrollSpeed {
    _scrollSpeed = MAX(scrollSpeed, 10); // 设置最小速度
    _scrollStep = _scrollSpeed / 60.0;   // 60fps下的每帧移动量
}

#pragma mark - Animation Control
- (void)stopScrolling {
    self.isScrolling = NO;
    if (self.displayLink) {
        [self.displayLink invalidate];
        self.displayLink = nil;
    }
}

- (void)restartScrolling {
    if (!_needsScrolling) {
        [self stopScrolling];
        return;
    }
    
    // 确保显示所有内容
    _label2.hidden = NO;
    
    // 如果已经滚动则不需要重启
    if (self.isScrolling) {
        return;
    }
    
    // 设置滚动状态
    self.isScrolling = YES;
    
    // 创建display link用于动画
    if (!self.displayLink) {
        self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(step)];
        [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    }
}

- (void)step {
    if (!self.isScrolling) return;
    
    CFTimeInterval currentTime = CACurrentMediaTime();
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = currentTime;
        return;
    }
    
    // 计算时间间隔并更新内容偏移
    CFTimeInterval delta = currentTime - self.lastUpdateTime;
    self.lastUpdateTime = currentTime;
    
    // 更新滚动位置
    _contentOffset -= _scrollSpeed * delta;
    [self updateContainerPosition];
}

- (void)dealloc {
    [self stopScrolling];
}

@end
